package cn.tjad.tjad2.module.form.views;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;

import cn.tjad.tjad2.BuildConfig;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.data.bean.FormDetail;

public class SingleLineTextView extends FormBaseLayout {

    private EditText editText;

    public SingleLineTextView(Context context) {
        super(context);
    }

    public SingleLineTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init() {
        super.init();
        addBodyView();
    }

    @Override
    public void setFormStepDetail(FormDetail.FormStepDetail formStepDetail) {
        super.setFormStepDetail(formStepDetail);
        bindText();
    }

    private void addBodyView() {
        editText = new EditText(getContext());
        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
//                editText.setEnabled(false);
        editText.setMaxLines(1);
        editText.setPadding(5, 3, 5, 3);
        editText.setGravity(Gravity.LEFT);
        editText.setBackgroundResource(R.drawable.file_input_text_bg);
        editText.setTextColor(Color.parseColor("#101010"));
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        this.setLayoutParams(lp);
        LayoutParams lp2 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        this.addView(editText, lp2);
    }

    private void bindText() {
        if (formStepDetail.value != null) {
            editText.setText(formStepDetail.value);
        }
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                formStepDetail.value = s.toString();
                if (onEditListener != null) {
                    onEditListener.onEdit(formStepDetail.detail.id, s.toString());
                }
                if (BuildConfig.DEBUG) {
                    Log.d("TJAD", "单行输入框：" + s.toString());
                }
            }
        });
    }

    @Override
    public String getValue() {
        return editText.getText().toString();
    }
}
